import React, { useEffect, useState } from 'react'
import { Button, notification, Table } from 'antd'
import { roleObj } from '@/utils/const'
import { getNewsListApi, updateNewsApi } from '@/api/news'

function Audit() {
  // roleId  1 超级管理员 2 区域 管理员 3 区域编辑
  const { roleId, region, username } = JSON.parse(localStorage.getItem('token'))
  // 数据源，渲染前端
  const [dataSource, setDataSource] = useState([])

  useEffect(() => {
    getNewsList()
  }, [roleId, region, username])

  // 获取列表
  const getNewsList = () => {
    getNewsListApi({
      auditState: 1,
      '_expand': 'category'
    }).then(res => {
      const list = res
      setDataSource(
        roleObj[roleId] === 'superadmin' ? list : [
          ...list.filter((item) => item.author === username),
          ...list.filter(
            (item) =>
              item.region === region &&
                    roleObj[item.roleId] === 'editor' &&
                    item.username !== username
          )
        ]
      )
    })
  }

  // 通过
  const handlePass = (item) => {
    updateNewsApi(item.id, {
      ...item,
      auditState: 2,
      publishState: 1
    }).then(() => {
      getNewsList()
      // 通知用户
      notification.info({
        message: '通知',
        description: '您已审核通过此新闻',
        placement: 'bottomRight'
      })
    })
  }

  // 驳回
  const handleFail = (item) => {
    updateNewsApi(item.id, {
      ...item,
      auditState: 3
    }).then(() => {
      getNewsList()
      notification.info({
        message: '通知',
        description: '您已审核驳回此新闻',
        placement: 'bottomRight'
      })
    })
  }

  const columns = [
    {
      title: '新闻标题',
      dataIndex: 'title',
      render: (title, item) => {
        return <a href={`#/news-manage/preview/${item.id}`}>{title}</a>
      }
    },
    {
      title: '作者',
      dataIndex: 'author'
    },
    {
      title: '新闻分类',
      dataIndex: 'category',
      render: (category) => {
        return category.value
      }
    },
    {
      title: '操作',
      render: (item) => {
        return <div>
          <Button onClick={() => handlePass(item)} type="primary">通过</Button>
          &nbsp;&nbsp;
          <Button danger onClick={() => handleFail(item)}>驳回</Button>
        </div>
      }
    }
  ]

  return (
    <div>
      <Table
        columns={columns}
        dataSource={dataSource}
        pagination={{ pageSize: 5 }}
        rowKey={item => item.id}
      />
    </div>
  )
}

export default Audit